package common;

import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

/**
 * Created by sshong on 15/6/1.
 */
public class VideoWebChromeClient extends WebChromeClient {
    private WebView webView;
    private ViewGroup fullWebViewContainer;
    private VideoFullScreenHandler handler;

    private View mCustomView;
    private CustomViewCallback customViewCallback;

    public VideoWebChromeClient(WebView webview, ViewGroup fullWebViewContainer, VideoFullScreenHandler handler) {
        this.webView = webview;
        this.fullWebViewContainer = fullWebViewContainer;
        this.handler = handler;
    }

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {

        // if a view already exists then immediately terminate the new one
        if (mCustomView != null) {
            callback.onCustomViewHidden();
            return;
        }
        mCustomView = view;
        webView.setVisibility(View.GONE);
        fullWebViewContainer.setVisibility(View.VISIBLE);
        fullWebViewContainer.addView(view);
        customViewCallback = callback;

        handler.onFullScreen();
    }

    @Override
    public void onHideCustomView() {
        super.onHideCustomView();    //To change body of overridden methods use File | Settings | File Templates.
        if (mCustomView == null) {
            return;
        }

        webView.setVisibility(View.VISIBLE);
        fullWebViewContainer.setVisibility(View.GONE);

        // Hide the custom view.
        mCustomView.setVisibility(View.GONE);

        // Remove the custom view from its container.
        fullWebViewContainer.removeView(mCustomView);
        customViewCallback.onCustomViewHidden();

        mCustomView = null;

        handler.onExitFullScreen();
    }

    public boolean inCustomView() {
        return (mCustomView != null);
    }

    public interface VideoFullScreenHandler {
        public void onFullScreen();

        public void onExitFullScreen();
    }
}

